package com.pureut.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pureut.order.domain.CustomerManagement;
import com.pureut.order.domain.SalesOrder;
import com.pureut.order.domain.SalesOrderDetail;
import com.pureut.order.dto.*;
import com.pureut.order.mapper.CustomerManagementMapper;
import com.pureut.order.mapper.SalesOrderDetailMapper;
import com.pureut.order.mapper.SalesOrderMapper;
import com.pureut.order.service.SalesOrderService;
import com.pureut.order.vo.*;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.domain.R;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.dict.utils.DictUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.redis.utils.RedisUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.order.api.dto.SaleServiceDto;
import com.sale.order.api.vo.SaleServiceVo;
import com.sale.order.api.vo.UpdateSaleOrderVo;
import com.sale.system.api.*;
import com.sale.system.api.domain.SysAuxiliary;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.dto.SysCustomDto;
import com.sale.system.api.domain.dto.SysStaffManagementDto;
import com.sale.system.api.domain.vo.SysAuditHistoryVo;
import com.sale.system.api.domain.vo.SysWorkbenchAuditAgentDubboVo;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 销售订单实现层
 * Author:C
 * Date:2022/11/30 17:57
 * @DESC
 */
@Service
@RequiredArgsConstructor
public class SalesOrderServiceImpl implements SalesOrderService {

    private final SalesOrderMapper salesOrderMapper;
    @DubboReference
    RemoteStaffManagementService remoteStaffManagementService;

    private final SalesOrderDetailMapper salesOrderDetailMapper;

    private final CustomerManagementMapper customerManagementMapper;

    @DubboReference
    private final RemoteCodeService remoteCodeService;

    @DubboReference
    private final RemoteReviewService remoteReviewService;

    @DubboReference
    RemoteUnitService remoteUnitService;

    @DubboReference
    RemoteWorkbenchMessageService remoteWorkbenchMessageService;


    /**
     * 销售订单列表
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    public TableDataInfo<Map<String, String>> getList(SalesOrderVo salesOrderVo, PageQuery pageQuery) {
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_order_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //表名
        String tableName = "`ry-order`.sales_order";
        //通过缓存获取自定义表头信息
        String userIdStr = LoginHelper.getUserIdStr();
        String tenantId = RedisUtils.getCacheObject(userIdStr);
        List<com.sale.system.api.domain.dto.SysCustomDto> titleMessage = CacheUtils.get(CacheNames.SYS_CUSTOM + "_" + tenantId, tableName);
        StringBuilder stringBuilder = new StringBuilder();
        String code = "";
        Page<Map<String, String>> salesOrderList = null;
        if (titleMessage != null) {
            for (SysCustomDto entity : titleMessage) {
                stringBuilder.append(",").append("a.").append(entity.getFieldsModel());
            }
            code = stringBuilder.toString();
            //销售订单列表
            salesOrderList = salesOrderMapper.getSalesOrderList(code, pageQuery.build(), salesOrderVo);
        } else {
            //销售订单列表
            salesOrderList = salesOrderMapper.getSalesOrderList(code, pageQuery.build(), salesOrderVo);
        }

        List<Map<String, String>> list = salesOrderList.getRecords();
        for (Map<String, String> map : list) {
            //销售订单状态
            map.put("statusDict", statusMap.get(map.get("status")));
            //销售人员
            Long staffId = Long.valueOf(map.get("attributor"));
            map.put("attributorDict", remoteStaffManagementService.getInfo(staffId).getData().getStaffName());
        }
//        for (SalesOrderDto entity : records) {
//            //销售订单状态
//            entity.setStatusDict(statusMap.get(entity.getStatus()));
//            //销售人员
//            Long staffId = Long.valueOf(entity.getAttributor());
//            entity.setAttributorDict(remoteStaffManagementService.getInfo(staffId).getData().getStaffName());
//        }
        return TableDataInfo.build(salesOrderList);
    }

    /**
     * 新增销售订单
     *
     * @param map
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addSalesOrder(Map<String,Object> map) throws Exception {
        //保存销售订单
//        SalesOrder salesOrder = new SalesOrder();
//        BeanUtils.copyProperties(salesOrderVo, salesOrder);
        String authorityCoding = remoteCodeService.authorityCoding("order:saleOrder:list");
        if (authorityCoding == null) {
            throw new GlobalException("未进行单据配置,单据编码生成失败");
        }
        //表名
        String tableName = "`ry-order`.sales_order";
        //通过缓存获取自定义表头信息
        String userIdStr = LoginHelper.getUserIdStr();
        String tenantId = RedisUtils.getCacheObject(userIdStr);
        List<SysCustomDto> titleMessage = CacheUtils.get(CacheNames.SYS_CUSTOM + "_" + tenantId, tableName);
        StringBuilder stringBuilder = new StringBuilder();
        String code = "";
        if (titleMessage != null) {
            for (SysCustomDto entity : titleMessage) {
                stringBuilder.append(",").append(entity.getFieldsModel());
            }
            code = stringBuilder.toString();
        }
        Map<String, Object> addMap = new LinkedHashMap<>();
        addMap.put("attributor", map.get("attributor"));
        addMap.put("customerNum", map.get("customerNum"));
        addMap.put("billingDate", map.get("billingDate"));
        addMap.put("remark", map.get("remark"));
        addMap.put("createBy", LoginHelper.getUsername());
        addMap.put("createTime", new Date());
        addMap.put("status", 1);
        addMap.put("salesOrderNum", authorityCoding);
        if (titleMessage != null) {
            for (SysCustomDto entity1 : titleMessage) {
                addMap.put(entity1.getFieldsModel(), map.get(entity1.getFieldsModel()));
            }
        }
        boolean b = salesOrderMapper.insertMessage(code, addMap);
//        salesOrder.setAttributor(salesOrderVo.getAttributor())
//            .setCustomerNum(salesOrderVo.getCustomerNum())
//            .setBillingDate(salesOrderVo.getBillingDate())
//            .setRemark(salesOrderVo.getRemark())
//            .setCreateBy(LoginHelper.getUsername())
//            .setCreateTime(new Date())
//            .setStatus(1)
//            .setSalesOrderNum(authorityCoding);
//        int insert = salesOrderMapper.insert(salesOrder);
        //保存销售订单明细信息
        List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
            if (b) {
                Object materialList1 = map.get("salesOrderDetailList");
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonString = objectMapper.writeValueAsString(materialList1);
                List<SalesOrderDetailDto> detailList = JSON.parseArray(jsonString, SalesOrderDetailDto.class);
                //获取新增的销售订单
                SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, authorityCoding));
//                List<SalesOrderDetailDto> detailList = salesOrderVo.getSalesOrderDetailList();
                if (detailList != null && detailList.size() > 0) {
                    for (SalesOrderDetailDto entity : detailList) {
                        SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
//                        BeanUtils.copyProperties(entity, salesOrderDetail);
                        salesOrderDetail
                            .setMaterialUnit(entity.getMaterialUnit())
                            .setCreateBy(LoginHelper.getUsername())
                            .setMaterialCode(entity.getMaterialCode())
                            .setSocketNumber(entity.getSocketNumber())
                            .setUnitPrice(entity.getUnitPrice())
                            .setDeliveryDate(entity.getDeliveryDate())
                            .setCreateTime(new Date())
                            .setOrderDetailStatus(7)
                            .setSalesOrderId(salesOrder.getId())
                            .setMaterialCategory(map.get("materialCategory").toString());
                        salesOrderDetailList.add(salesOrderDetail);
                    }
                }
                return salesOrderDetailMapper.insertBatch(salesOrderDetailList);
            } else {
                throw new GlobalException("保存失败");
            }
    }

    /**
     * 提交评审
     *
     * @param id
     * @return
     */
    @Override
    public boolean submitReview(Long id) {
        SalesOrder salesOrder = salesOrderMapper.selectById(id);
        if (salesOrder.getStatus() == 1) {
            salesOrder.setStatus(2);
            boolean b = salesOrderMapper.updateById(salesOrder) > 0;
            if (b) {
                List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, id));
                for (SalesOrderDetail entity : salesOrderDetails) {
                    entity.setOrderDetailStatus(1);
                }
                salesOrderDetailMapper.updateBatchById(salesOrderDetails);
            }
            SysWorkbenchAuditAgentDubboVo sysWorkbenchAuditAgentDubboVo = new SysWorkbenchAuditAgentDubboVo();
            sysWorkbenchAuditAgentDubboVo.setDocConfig("order:saleOrder:examine");
            sysWorkbenchAuditAgentDubboVo.setReceiptName("销售订单");
            sysWorkbenchAuditAgentDubboVo.setReceiptNumber(salesOrder.getSalesOrderNum());
            sysWorkbenchAuditAgentDubboVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentDubboVo.setReceiptContent("有单据待审核,请及时审核");

            remoteWorkbenchMessageService.insertAuditAgent(sysWorkbenchAuditAgentDubboVo);
            return b;
//            return salesOrderDetailMapper.updateBatchById(salesOrderDetailList);
        } else {
            throw new GlobalException("只能对待提交的订单进行操作");
        }

    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteReview(Long id) {
        SalesOrder salesOrder = salesOrderMapper.selectById(id);
        if (2 == salesOrder.getStatus()) {
            salesOrder.setStatus(1);
            boolean b = salesOrderMapper.updateById(salesOrder) > 0;
            if (b) {
                List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, id));
                for (SalesOrderDetail entity : salesOrderDetails) {
                    if (entity.getOrderDetailStatus() == 1) {
                        entity.setOrderDetailStatus(7);
                    }
                }
                salesOrderDetailMapper.updateBatchById(salesOrderDetails);
            }
            remoteWorkbenchMessageService.deleteDoc(salesOrder.getSalesOrderNum(), "销售订单");
            return b;
//            return salesOrderDetailMapper.updateBatchById(salesOrderDetailList);
        } else {
            throw new GlobalException("只能撤销待审核的销售订单");
        }
    }

    /**
     * 手动关结
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean close(SalesOrderVo salesOrderVo) {
        SalesOrder salesOrder = salesOrderMapper.selectById(salesOrderVo.getId());
        if (salesOrder.getStatus() == 6 || salesOrder.getStatus() == 7) {
            throw new GlobalException("不能操作已完成、已关节的单据");
        }
        salesOrder.setStatus(7);
        salesOrder.setCloseReason(salesOrderVo.getCloseReason());
        boolean b = salesOrderMapper.updateById(salesOrder) > 0;
        //销售订单关结时，需要校验销售订单下的明细状态，只有明细状态全为“已完成”或“已终止”时才允许进行关结，关结后单据状态更新为“已关结”，明细状态不变
//        boolean isAll = true;
//        for (SalesOrderDetail entity : salesOrderDetails) {
//            if (entity.getOrderDetailStatus() != 6 || entity.getOrderDetailStatus() != 8) {
//                isAll = false;
//                break;
//            }
//        }
        if (b) {
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
            for (SalesOrderDetail entity : salesOrderDetails) {
                entity.setOrderDetailStatus(6);
            }
            return salesOrderDetailMapper.updateBatchById(salesOrderDetails);
        } else {
            throw new GlobalException("明细状态全为“已完成”或“已终止”时才允许进行关结该单据");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        if (idList.size() > 0) {
            List<SalesOrder> salesOrders = new ArrayList<>();
            List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
            //获取销售订单列表
            List<SalesOrder> salesOrderList = salesOrderMapper.selectList(new QueryWrapper<SalesOrder>().lambda().in(SalesOrder::getId, idList));
            for (SalesOrder entity : salesOrderList) {
                boolean status = 1 == entity.getStatus();
                if (status) {
                    salesOrders.add(entity);

                    remoteWorkbenchMessageService.deleteDoc(entity.getSalesOrderNum(), "销售订单");

                } else {
                    throw new GlobalException("只能删除待提交的订单");
                }
            }
            //判断是否存在明细数据以及状态是否为待提交或者未通过
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().in(SalesOrderDetail::getSalesOrderId, idList));
            for (SalesOrderDetail salesOrderDetail : salesOrderDetails) {
                boolean status = 2 == salesOrderDetail.getOrderDetailStatus() || 7 == salesOrderDetail.getOrderDetailStatus();
                if (status) {
                    salesOrderDetailList.add(salesOrderDetail);
                }
            }
            if (salesOrders.size() > 0 && salesOrderDetailList.size() > 0) {
                salesOrderMapper.deleteBatchIds(salesOrders);
                return salesOrderDetailMapper.deleteBatchIds(salesOrderDetailList) > 0;
            } else {
                throw new GlobalException("没有满足删除条件的订单");
            }
        }
        return false;
    }

    /**
     * 修改销售订单
     *
     * @param map
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSalesOrder(Map<String,Object> map) throws SQLException {
        Long id = Long.valueOf(map.get("id").toString());
        //获取销售订单
        SalesOrder salesOrder = salesOrderMapper.selectById(id);
        //表名
        String tableName = "`ry-order`.sales_order";
        //通过缓存获取自定义表头信息
        String userIdStr = LoginHelper.getUserIdStr();
        String tenantId = RedisUtils.getCacheObject(userIdStr);
        List<SysCustomDto> titleMessage = CacheUtils.get(CacheNames.SYS_CUSTOM + "_" + tenantId, tableName);
        //判断单据状态进行修改
        if (1 == salesOrder.getStatus()) {
            //修改销售订单
            Map<String, Object> updateMap = new LinkedHashMap<>();
            updateMap.put("attributor", map.get("attributor"));
            updateMap.put("customer_num", map.get("customerNum"));
            updateMap.put("billing_date", map.get("billingDate"));
            updateMap.put("remark", map.get("remark"));
            if (titleMessage != null) {
                for (SysCustomDto entity1 : titleMessage) {
                    updateMap.put(entity1.getFieldsModel(), map.get(entity1.getFieldsModel()));
                }
            }
//            BeanUtils.copyProperties(salesOrderVo, salesOrder);
//            salesOrderMapper.updateById(salesOrder);
            salesOrderMapper.updateSalesOrder(id, updateMap);
            //修改销售订单明细
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>()
                .lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
            int i = salesOrderDetailMapper.deleteBatchIds(salesOrderDetails);
            //保存销售订单明细信息
            List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
            try {
                if (i > 0) {
                    Object materialList1 = map.get("salesOrderDetailList");
                    ObjectMapper objectMapper = new ObjectMapper();
                    String jsonString = objectMapper.writeValueAsString(materialList1);
                    List<SalesOrderDetailDto> detailList = JSON.parseArray(jsonString, SalesOrderDetailDto.class);
//                    List<SalesOrderDetailDto> detailList = salesOrderVo.getSalesOrderDetailList();
                    if (detailList != null && detailList.size() > 0) {
                        for (SalesOrderDetailDto entity : detailList) {
                            SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
//                            BeanUtils.copyProperties(entity, salesOrderDetail);
                            salesOrderDetail
                                .setMaterialCategory(String.valueOf(entity.getMaterialCategory()))
                                .setMaterialUnit(entity.getMaterialUnit())
                                .setCreateBy(LoginHelper.getUsername())
                                .setMaterialCode(entity.getMaterialCode())
                                .setSocketNumber(entity.getSocketNumber())
                                .setUnitPrice(entity.getUnitPrice())
                                .setDeliveryDate(entity.getDeliveryDate())
                                .setCreateTime(new Date())
                                .setOrderDetailStatus(7)
                                .setSalesOrderId(salesOrder.getId());
                            salesOrderDetailList.add(salesOrderDetail);

                            //修改审核代办状态为已处理
                            remoteWorkbenchMessageService.updateStatus(3, entity.getSalesOrderNum(), "销售订单");
                        }
                    }
                    return salesOrderDetailMapper.insertBatch(salesOrderDetailList);
                } else {
                    throw new GlobalException("保存失败");
                }
            } catch (Exception e) {
                throw new SQLException("批量保存失败");
            }
        } else {
            throw new GlobalException("只能修改待提交的数据");
        }
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public Map<String,Object> getView(Long id) {
        Map<String, Object> map = new HashMap<>();
//        SalesOrderViewDto salesOrderViewDto = new SalesOrderViewDto();
        //表名
        String tableName = "`ry-order`.sales_order";
        //通过缓存获取自定义表头信息
        String userIdStr = LoginHelper.getUserIdStr();
        String tenantId = RedisUtils.getCacheObject(userIdStr);
        List<SysCustomDto> titleMessage = CacheUtils.get(CacheNames.SYS_CUSTOM + "_" + tenantId, tableName);

        //获取销售订单信息
        Map<String, Object> viewById = salesOrderMapper.getViewById(id);
        if (titleMessage != null) {
            for (SysCustomDto entity : titleMessage) {
                if(viewById.get(entity.getFieldsModel()) != null){
                    map.put(entity.getFieldsModel(),viewById.get(entity.getFieldsModel()));
                }
            }
        }

//        BeanUtils.copyProperties(salesOrder, salesOrderViewDto);

        if (viewById.get("attributor") != null) {
            //归属人
            Long staffId = Long.valueOf(viewById.get("attributor").toString());
            R<SysStaffManagementDto> info = remoteStaffManagementService.getInfo(staffId);
            if (info.getData() != null) {
                map.put("attributorDict", info.getData().getStaffName());
                map.put("attributor", viewById.get("attributor"));
//                salesOrderViewDto.setAttributorDict(info.getData().getStaffName());
            }
        }

        //获取客户信息
        CustomerManagement byId = customerManagementMapper.selectOne(new QueryWrapper<CustomerManagement>().lambda().eq(CustomerManagement::getCustomerNum, viewById.get("customerNum")));
        map.put("customerName",byId.getCustomerName());
        map.put("id",viewById.get("id"));
        map.put("customerCode",byId.getCustomerNum());
        map.put("orderType",String.valueOf(viewById.get("orderType")));
        map.put("orderPriority",String.valueOf(viewById.get("orderPriority")));
        map.put("billingDate",String.valueOf(viewById.get("billingDate")));
        map.put("remark",String.valueOf(viewById.get("remark")));
//        salesOrderViewDto.setCustomerName(byId.getCustomerName());
//        salesOrderViewDto.setCustomerCode(byId.getCustomerNum());
//        salesOrderViewDto.setOrderType(String.valueOf(salesOrder.getOrderType()));
//        salesOrderViewDto.setOrderPriority(String.valueOf(salesOrder.getOrderPriority()));

        //获取销售订单明细列表
        Page<SalesOrderDetailDto> detailList = salesOrderDetailMapper.getDetailList(new Page<>(), id);
        List<SalesOrderDetailDto> records = detailList.getRecords();

        for (SalesOrderDetailDto entity : records) {
            //类别
            if (entity.getMaterialCategory() == 1) {
                entity.setMaterialCategoryDict("原料");
            } else {
                entity.setMaterialCategoryDict("成品");
            }
            //辅助属性
            List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
            entity.setAuxiliaryAttribute(statsArray);
            //单位
            entity.setUnitDict(remoteUnitService.getUnitDataByCode(Long.parseLong(entity.getMaterialUnit())).getData().getUnitName());
        }
        map.put("salesOrderDetailList",records);
//        salesOrderViewDto.setSalesOrderDetailList(records);
        return map;
    }

    /**
     * 合同上传
     *
     * @param contractUploadVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean contractUpload(ContractUploadVo contractUploadVo) throws Exception {
        SalesOrder salesOrder = salesOrderMapper.selectById(contractUploadVo.getId());

        if (4 == salesOrder.getStatus()) {
            salesOrder.setContractUrl(contractUploadVo.getContractUrl());
            salesOrder.setSalesContractNum(contractUploadVo.getSalesContractNum());
            salesOrder.setStatus(5);
            salesOrderMapper.updateById(salesOrder);
            //获取明细数据
            Page<SalesOrderDetailDto> detailList = salesOrderDetailMapper.getDetailList(new Page<>(), contractUploadVo.getId());
            List<SalesOrderDetailDto> records = detailList.getRecords();
            List<Long> ids = new ArrayList<>();
            for (SalesOrderDetailDto entity : records) {
                ids.add(entity.getId());
            }
            List<SalesOrderDetail> salesOrderDetailList1 = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().in(SalesOrderDetail::getId, ids));
            List<SalesOrderDetail> salesOrderDetails = new ArrayList<>();
            for (SalesOrderDetail entity : salesOrderDetailList1) {
                entity.setOrderDetailStatus(4);
                salesOrderDetails.add(entity);
            }
            return salesOrderDetailMapper.updateBatchById(salesOrderDetails);
        } else {
            throw new GlobalException("只能对待签订的订单进行上传");
        }
    }

    /**
     * 销售订单审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saleOrderReview(OrderReviewVo orderReviewVo) throws Exception {

        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectOne(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getId, orderReviewVo.getId()));
        //获取销售订单数据
        SalesOrder salesOrder1 = salesOrderMapper.selectById(salesOrderDetail.getSalesOrderId());
        if (salesOrderDetail.getOrderDetailStatus() == 1) {
            String perms = "order:saleOrder:examine";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = salesOrder1.getSalesOrderNum() + salesOrderDetail.getId();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = LoginHelper.getUserId();
            SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
            sysAuditHistoryVo.setPerms(perms);
            sysAuditHistoryVo.setModuleType(2);
            sysAuditHistoryVo.setAuditState(isAdopt);
            sysAuditHistoryVo.setAuditRemarks(auditRemarks);
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setUserId(userId);
            int data = remoteReviewService.getSequence(sysAuditHistoryVo);
            if (data == 0) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                //同意审核
                if (data == 1) {
                    salesOrderDetail.setOrderDetailStatus(3);
                    //获取订单信息
                    SalesOrder salesOrder = salesOrderMapper.selectById(salesOrderDetail.getSalesOrderId());
                    if (salesOrder.getReviewBy() == null) {
                        salesOrder.setReviewBy(LoginHelper.getUsername());
                    } else {
                        salesOrder.setReviewBy(salesOrder.getReviewBy() + "," + LoginHelper.getUsername());
                    }
                    salesOrder.setReviewTime(new Date());
                    int i = salesOrderDetailMapper.updateById(salesOrderDetail);
                    //获取明细列表，判断每一条的状态
                    List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>()
                        .lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrderDetail.getSalesOrderId()));
                    boolean isTrue = true;
                    for (SalesOrderDetail entity : salesOrderDetailList) {
                        if (entity.getOrderDetailStatus() != 3) {
                            isTrue = false;
                            break;
                        }
                    }
                    if (isTrue) {
                        salesOrder.setStatus(4);
                    } else {
                        salesOrder.setStatus(3);
                    }
                    salesOrderMapper.updateById(salesOrder);

                    remoteWorkbenchMessageService.updateStatus(3, salesOrder.getSalesOrderNum(), "销售订单");

                    return i > 0;
                } else if (data == 2) {
                    salesOrderDetail.setOrderDetailStatus(3);
                    //获取订单信息
                    SalesOrder salesOrder = salesOrderMapper.selectById(salesOrderDetail.getSalesOrderId());
                    if (salesOrder.getReviewBy() == null) {
                        salesOrder.setReviewBy(LoginHelper.getUsername());
                    } else {
                        salesOrder.setReviewBy(salesOrder.getReviewBy() + "," + LoginHelper.getUsername());
                    }
                    salesOrder.setReviewTime(new Date());
                    salesOrder.setStatus(3);
                    salesOrderDetailMapper.updateById(salesOrderDetail);
                    return salesOrderMapper.updateById(salesOrder) > 0;
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    salesOrderDetail.setOrderDetailStatus(2);
                    //获取订单信息
                    SalesOrder salesOrder = salesOrderMapper.selectById(salesOrderDetail.getSalesOrderId());
                    if (salesOrder.getReviewBy() == null) {
                        salesOrder.setReviewBy(LoginHelper.getUsername());
                    } else {
                        salesOrder.setReviewBy(salesOrder.getReviewBy() + "," + LoginHelper.getUsername());
                    }
                    salesOrder.setStatus(3);
                    salesOrder.setReviewTime(new Date());
                    salesOrderDetailMapper.updateById(salesOrderDetail);

                    SysWorkbenchAuditAgentDubboVo sysWorkbenchAuditAgentDubboVo = new SysWorkbenchAuditAgentDubboVo();
                    sysWorkbenchAuditAgentDubboVo.setDocConfig("order:saleOrder:examine");
                    sysWorkbenchAuditAgentDubboVo.setReceiptName("销售订单");
                    sysWorkbenchAuditAgentDubboVo.setReceiptNumber(salesOrder.getSalesOrderNum());//
                    sysWorkbenchAuditAgentDubboVo.setStatus(2);//待处理
                    sysWorkbenchAuditAgentDubboVo.setReceiptContent("有单据未通过,请及时查看");
                    sysWorkbenchAuditAgentDubboVo.setPassFlag("1");
                    sysWorkbenchAuditAgentDubboVo.setCreateName(salesOrder.getCreateBy());

                    remoteWorkbenchMessageService.insertAuditAgent(sysWorkbenchAuditAgentDubboVo);
                    return salesOrderMapper.updateById(salesOrder) > 0;
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核单据才能进行审核");
        }
    }

    /**
     * 获取销售订单列表(其他模块调用)
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    public TableDataInfo<SalesOrderDto> getSaleOrderList(SalesOrderVo salesOrderVo, PageQuery pageQuery) {
        //销售订单列表
        Page<SalesOrderDto> orderSalesOrderList = salesOrderMapper.getOrderSalesOrderList(pageQuery.build(), salesOrderVo);
        List<SalesOrderDto> records = orderSalesOrderList.getRecords();
        //获取销售订单状态缓存字典数据
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_order_status");
        Map<String, String> actualMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (SalesOrderDto entity : records) {
            //类别
            if (entity.getMaterialCategory() == 1) {
                entity.setMaterialCategoryDict("原料");
            } else {
                entity.setMaterialCategoryDict("成品");
            }
            //辅助属性
            List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
            entity.setAuxiliaryAttribute(statsArray);

            String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(entity.getMaterialUnit())).getData().getUnitName();
            //单位
            entity.setMaterialUnitDict(unitName);
            //获取销售订单状态缓存字典数据
            entity.setStatusDict(actualMap.get(entity.getStatus()));
        }
        return TableDataInfo.build(orderSalesOrderList);
    }

//    /**
//     * 排程模块回传数据，修改销售订单状态及数据（feign调用）
//     *
//     * @param updateDataBySchedulingVo
//     * @return
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean updateDataByScheduling(UpdateDataBySchedulingVo updateDataBySchedulingVo) {
//        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, updateDataBySchedulingVo.getSalesOrderNum()));
//        //根据销售订单号获取明细
//        List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
//        //获取回传列表
//        List<SalesMaterialDataVo> materialList = updateDataBySchedulingVo.getMaterialList();
//
//        for (SalesOrderDetail entity1 : salesOrderDetailList) {
//            for (SalesMaterialDataVo entity2 : materialList) {
//                if (entity1.getMaterialCode().equals(entity2.getMaterialCode())) {
//                    entity1.setProducedWeight(entity2.getProducedWeight());
//                    entity1.setNoProducedWeight(entity2.getNoProducedWeight());
//                    entity1.setShippingWeight(entity2.getShippingWeight());
//                    entity1.setBackWeight(entity2.getBackWeight());
//                    entity1.setOrderDetailStatus(entity2.getStatus());
//                }
//            }
//        }
//        //修改明细
//        boolean b = salesOrderDetailService.updateBatchById(salesOrderDetailList);
//        if (b) {
//            boolean isAll = true;
//            for (SalesOrderDetail entity : salesOrderDetailList) {
//                if (entity.getOrderDetailStatus() != 8) {
//                    isAll = false;
//                    break;
//                }
//            }
//            //如果修改之后明细都为已经完成，就修改销售订单状态为已完成
//            if (isAll) {
//                salesOrder.setStatus(6);
//                return updateById(salesOrder);
//            }
//        }
//        return b;
//    }

    /**
     * 根据销售订单号及物料编码获取明细信息
     *
     * @param saleNumber
     * @param materialCode
     * @return
     */
    @Override
    public SalesOrderDetailDto getDataBySaleNumberAndMaterialCode(String saleNumber, String materialCode) {
        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取铺网类型标准缓存字典数据
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取采购计划质量标准
        List<SysDictData> standardArray = DictUtils.getDictCache("quality_standard");
        Map<String, String> standardMap = standardArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取销售订单
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, saleNumber));
        //获取明细
        Page<SalesOrderDetailDto> detailList = salesOrderDetailMapper.getDetailList(new Page<>(), salesOrder.getId());
        List<SalesOrderDetailDto> records = detailList.getRecords();
        SalesOrderDetailDto salesOrderDetailDto = new SalesOrderDetailDto();
        for (SalesOrderDetailDto entity : records) {
            if (entity.getMaterialCode().equals(materialCode)) {
                BeanUtils.copyProperties(entity, salesOrderDetailDto);
            }
        }
        salesOrderDetailDto.setMaterialNetTypeDict(netTypeMap.get(salesOrderDetailDto.getMaterialNetType()));
        salesOrderDetailDto.setMaterialNetDict(netMap.get(salesOrderDetailDto.getMaterialNet()));
        salesOrderDetailDto.setQualityStandardDict(standardMap.get(salesOrderDetailDto.getQualityStandard()));
        return salesOrderDetailDto;
    }

    /**
     * 根据销售订单修改对应明细状态（生产计划 feign调用）
     *
     * @param updateSaleOrderDetailStatusVo
     */
    @Override
    public void updateSaleOrderDetailStatus(UpdateSaleOrderDetailStatusVo updateSaleOrderDetailStatusVo) {
        //获取销售订单
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, updateSaleOrderDetailStatusVo.getSaleOrderNo()));

        List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        for (SalesOrderDetail entity : salesOrderDetailList) {
            if (entity.getMaterialCode().equals(updateSaleOrderDetailStatusVo.getMaterialCode())) {
                entity.setOrderDetailStatus(updateSaleOrderDetailStatusVo.getStatus());
                salesOrderDetailMapper.updateById(entity);
            }
        }
    }

    /**
     * 成品称重页面回传数据至销售订单(成品称重 feign调用)
     *
     * @param backDataVo
     */
    @Override
    public void backData(BackDataVo backDataVo) {
        //根据销售订单号获取明细
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, backDataVo.getSaleNumber()));
        List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));


        for (SalesOrderDetail entity : salesOrderDetailList) {
            if (entity.getMaterialCode().equals(backDataVo.getMaterialCode())) {
                if (entity.getProducedWeight() == null) {
                    //委外重量
                    double subcontractWeight = entity.getSubcontractWeight();
                    //已生产重量
                    entity.setProducedWeight(String.valueOf(backDataVo.getNetWeight()));
                    //计划重量
                    BigDecimal bigDecimal = new BigDecimal(entity.getPlanWeight());
                    //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                    BigDecimal subtract1 = bigDecimal.subtract(new BigDecimal(String.valueOf(backDataVo.getNetWeight())));
                    BigDecimal subtract2 = subtract1.subtract(new BigDecimal(String.valueOf(subcontractWeight)));

                    entity.setNoProducedWeight(subtract2.toString());
                } else {
                    BigDecimal add = new BigDecimal(entity.getProducedWeight()).add(new BigDecimal(String.valueOf(backDataVo.getNetWeight())));
                    //计划重量
                    BigDecimal bigDecimal = new BigDecimal(entity.getPlanWeight());
                    //委外重量
                    double subcontractWeight = entity.getSubcontractWeight();
                    //已生产重量
                    entity.setProducedWeight(add.toString());
                    //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                    BigDecimal subtract1 = bigDecimal.subtract(new BigDecimal(String.valueOf(add.toString())));
                    BigDecimal subtract2 = subtract1.subtract(new BigDecimal(String.valueOf(subcontractWeight)));
                    entity.setNoProducedWeight(subtract2.toString());
                }
                if (entity.getProducedWeight().equals(entity.getPlanWeight())) {
                    entity.setOrderDetailStatus(8);
                }
                salesOrderDetailMapper.updateById(entity);
            }
        }
    }

    /**
     * 销售发货回传发货重量
     *
     * @param backDataVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateShippingWeight(BackDataVo backDataVo) {

        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getShippingWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getShippingWeight();
        }


        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(String.valueOf(backDataVo.getNetWeight()));

        BigDecimal add1 = shippingBig.add(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));
        int i = salesOrderMapper.updateShippingWeight(backDataVo);
        if (i > 0) {
            //判断该明细数量和发货量是否相等
            Long id = salesOrderDetail.getId();
            SalesOrderDetail salesOrderDetail1 = salesOrderDetailMapper.selectById(id);
            if (Double.parseDouble(salesOrderDetail1.getShippingWeight()) >= Double.parseDouble(String.valueOf(salesOrderDetail1.getSocketNumber()))) {
                salesOrderDetail1.setOrderDetailStatus(5);
            } else {
                salesOrderDetail1.setOrderDetailStatus(4);
            }
            salesOrderDetailMapper.updateById(salesOrderDetail1);
            //判断该单据下的明细是否都已完成，如果都完成销售订单变为已完成
            String saleNumber = backDataVo.getSaleNumber();
            SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>()
                .lambda().eq(SalesOrder::getSalesOrderNum, saleNumber));
            //获取销售订单下的明细数据
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>()
                .lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
            //判断明细数据是否都为已完成，如果是就把销售订单改为已完成
            boolean isAll = true;
            for (SalesOrderDetail entity : salesOrderDetails) {
                if (entity.getOrderDetailStatus() != 5) {
                    isAll = false;
                    break;
                }
            }
            if (isAll) {
                salesOrder.setStatus(6);
                salesOrderMapper.updateById(salesOrder);
            }
        }
        return i > 0;
    }

    /**
     * 销售发货重量回传扣减
     *
     * @param backDataVo
     */
    @Override
    public boolean updateShippingWeightSub(BackDataVo backDataVo) {
        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getShippingWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getShippingWeight();
        }

        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(backDataVo.getNetWeight());

        BigDecimal add1 = shippingBig.subtract(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));

        return salesOrderMapper.updateShippingWeight(backDataVo) > 0;
    }

    /**
     * 销售退货重量回传（）
     *
     * @param backDataVo
     * @return
     */
    @Override
    public boolean updateShippingOutWeight(BackDataVo backDataVo) {
        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getBackWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getBackWeight();
        }


        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(backDataVo.getNetWeight());

        BigDecimal add1 = shippingBig.add(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));

        return salesOrderMapper.updateShippingOutWeight(backDataVo);
    }

    /**
     * 销售发货扣除
     *
     * @param backDataVo
     * @return
     */
    @Override
    public boolean updateShippingWeightSubBack(BackDataVo backDataVo) {
        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getBackWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getBackWeight();
        }

        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(backDataVo.getNetWeight());

        BigDecimal add1 = shippingBig.subtract(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));

        return salesOrderMapper.updateShippingOutWeight(backDataVo);
    }

    /**
     * 委外入库回传销售订单明细委外重量(委外入库fegin调用)
     *
     * @param backDataVo
     * @return
     */
    @Override
    public boolean updateSubWeight(BackDataVo backDataVo) {
        //获取销售订单数据
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, backDataVo.getSaleNumber()));
        //获取该销售订单下的明细数据
        List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (backDataVo.getMaterialCode().equals(entity.getMaterialCode())) {
                if (entity.getSubcontractWeight() == 0) {
                    entity.setSubcontractWeight(backDataVo.getNetWeight());
                    //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                    BigDecimal subtract = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(entity.getProducedWeight()));
                    entity.setNoProducedWeight(subtract.toString());
                } else {
                    BigDecimal add = new BigDecimal(String.valueOf(backDataVo.getNetWeight())).add(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                    entity.setSubcontractWeight(Double.parseDouble(String.valueOf(add.toString())));
                    //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                    BigDecimal subtract = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(entity.getProducedWeight()));
                    BigDecimal subtract1 = subtract.subtract(new BigDecimal(String.valueOf(add.toString())));
                    entity.setNoProducedWeight(subtract1.toString());
                }
            }
        }
        return salesOrderDetailMapper.updateBatchById(salesOrderDetails);
    }

    /**
     * 销售发货回传重量（dubbo 调用）
     *
     * @param updateSaleOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSaleOrder(UpdateSaleOrderVo updateSaleOrderVo) {
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, updateSaleOrderVo.getSalesOrderNum()));

        //获取销售发货单回应明细数据
        List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (entity.getMaterialCode().equals(updateSaleOrderVo.getMaterialCode())) {
                if (entity.getShippingWeight() == null) {
                    entity.setShippingWeight(String.valueOf(updateSaleOrderVo.getNetWeight()));
                } else {
                    BigDecimal add = new BigDecimal(entity.getShippingWeight()).add(new BigDecimal(String.valueOf(updateSaleOrderVo.getNetWeight())));
                    entity.setShippingWeight(add.toString());
                }
                //判断改发货量是否大于该明细数量，如果大于等于该明细就为已完成
                Integer socketNumber = entity.getSocketNumber();
                int i = Integer.parseInt(entity.getShippingWeight());
                if (i >= socketNumber) {
                    entity.setOrderDetailStatus(5);
                }
            }
        }
        return salesOrderDetailMapper.updateBatchById(salesOrderDetails);
    }

    /**
     * 根据销售订单查出物料的单价（服务调用）
     */
    @Override
    public SaleServiceDto getSalePlace(SaleServiceVo saleServiceVo) {
        return salesOrderMapper.getSalePlace(saleServiceVo);
    }

    /**
     * 销售订单数(首页工作台使用)
     *
     * @return
     */
    @Override
    public String getSaleOrderNum() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sf.format(new Date());
        return salesOrderMapper.getSaleOrderNum(format);
    }


    /**
     * 销售订单金额（首页工作台使用）
     *
     * @return
     */
    @Override
    public String getSaleOrderPrice() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sf.format(new Date());
        return salesOrderMapper.getSaleOrderPrice(format);
    }


    /**
     * 前五大客户销售占比(元)
     */
    @Override
    public List<CustomerSaleRankDto> customerSaleRank() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sf.format(new Date());
        return salesOrderMapper.customerSaleRank(format);
    }

    /**
     * 获取销售订单明细中最新的信息集合(dubbo调用)
     */
    @Override
    public Map<String, Date> getNewSaleMap() {
        List<NewSaleMapDto> newSaleMap = salesOrderMapper.getNewSaleMap();
        Map<String, Date> map = new HashMap<>();
        for (NewSaleMapDto entity : newSaleMap) {
            map.put(entity.getSalesOrderNum(), entity.getDeliveryDate());
        }
        return map;
    }
}
